import React, { PureComponent } from 'react'
import Loading from '../loading'

export default (loader, componentProps) =>
  class AsyncComponent extends PureComponent {
    static Component = null

    state = {
      Component: AsyncComponent.Component,
    }

    componentWillMount() {
      if (!this.state.Component) {
        loader().then(Component => {
          AsyncComponent.Component = Component

          this.setState(() => ({
            Component,
          }))
        })
      }
    }

    componentWillUnmount() {
      this.loadingInstance && Loading.hide()
    }

    render() {
      const { Component } = this.state

      if (Component) {
        if (this.loadingInstance) {
          Loading.hide()
          this.loadingInstance = null
        }

        return <Component {...this.props} {...componentProps} />
      }

      if (!this.loadingInstance) {
        this.loadingInstance = Loading.show()
      }

      return null
    }
  }
